#!/bin/sh

e2e_test() {
  run_test "Checking that postgres configuration is reloaded" check_reload_postgres_configuration

  run_test "Checking that pgbouncer configuration is reloaded" check_reload_pgbouncer_configuration
}

check_reload_postgres_configuration() {
  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1 \
      --set-string configurations.postgresconfig.postgresql\\.conf.random_page_cost=
  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1 \
      --set-string configurations.postgresconfig.postgresql\\.conf.random_page_cost=1

  if wait_until eval "run_query -q \"SELECT setting FROM pg_settings WHERE name = 'random_page_cost'\" | grep -qxF 1" 
  then
    success "Postgres configuration has been updated"
  else
    fail "Postgres configuration has not been updated"
  fi
}

check_reload_pgbouncer_configuration() {
  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1 \
      --set-string configurations.poolingconfig.pgBouncer.pgbouncer\\.ini.client_idle_timeout=
  create_or_replace_cluster "$CLUSTER_NAME" "$CLUSTER_NAMESPACE" 1 \
      --set-string configurations.poolingconfig.pgBouncer.pgbouncer\\.ini.client_idle_timeout=750

  local PGBOUNCER_ADMIN_PASSWORD
  PGBOUNCER_ADMIN_PASSWORD="$(kubectl get secret -n "$CLUSTER_NAMESPACE" "$CLUSTER_NAME" --template '{{ index .data "pgbouncer-admin-password" | base64decode }}')"
  if wait_until eval "run_query -p 6432 -u 'pgbouncer_admin:$PGBOUNCER_ADMIN_PASSWORD' -d pgbouncer -q \"SHOW CONFIG\" | grep -q '^client_idle_timeout|750|'" 
  then
    success "PgBouncer configuration has been updated"
  else
    fail "PgBouncer configuration has not been updated"
  fi
}
